<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/14
 * Time: 14:22
 */

namespace app\forum\home;

use app\common\controller\ApiBase;
use app\forum\model\PostComment;
use app\forum\model\PostLike;

class Comment extends ApiBase
{

    /**
     * 留言列表
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function lists()
    {
        $input = $this->getInput("post_id", 1);
        $data = PostComment::getComments($input);

        return $this->apiReturn(compact("data"));
    }

    /**
     * 创建留言
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function create(){
        $input = $this->getInput(["post_id","content"],1);

        $comment = PostComment::create($input, ["user_id",'post_id', 'content']);

        return $this->apiReturn(["data" => $comment]);
    }

    /**
     * 删除留言
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function delete(){
        $input = $this->getInput(["comment_id"]);

        $comment = PostComment::get($input['comment_id']);
        if(!$comment || $comment->user_id != $this->getAuthorizeUID())
            return $this->apiError("留言不存在或权限不足！");

        $comment->delete();
        return $this->apiSuccess("删除成功！");
    }

    /**
     * 点赞
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function likeHandle(){
        $input = $this->getInput(["comment_id"]);
        $comment_id = $input["comment_id"];
        $user_id = $this->getAuthorizeUID();

        if(!PostComment::get($comment_id))
            return $this->apiError("留言不存在！");

        $data = PostLike::handle(compact("user_id","comment_id"));

        return $this->apiReturn($data);
    }
}